package com.leigq.springboot.easypoi.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateTime;
import com.google.common.collect.Lists;
import com.leigq.springboot.easypoi.handler.BatchAddCustomerExcelVerifyHandler;
import com.leigq.springboot.easypoi.param.BatchAddCustomerImportParam;
import com.leigq.springboot.easypoi.util.EasyPoiUtils;
import com.leigq.springboot.easypoi.vo.BatchAddCustomerExportVO;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * 批量加好友Controller
 *
 * @author leiguoqing
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/batchAddCustomer")
public class BatchAddCustomerController {

    /**
     * resources 目录下 Excel 文件，模拟前端上传
     */
    @Value("classpath:batchAddCustomer.xlsx")
    private Resource batchAddCustomerExcel;

    private final BatchAddCustomerExcelVerifyHandler batchAddCustomerExcelVerifyHandler;


    /**
     * 文件校验导入
     *
     * @param file the file
     * @param resp the resp
     * @return object string
     * @throws Exception the exception
     */
    @GetMapping("/excel/import")
    public String importTest(MultipartFile file, HttpServletResponse resp) throws Exception {
        // 模拟上传文件
        try (InputStream inputStream = batchAddCustomerExcel.getInputStream()) {
            // 导入的基本配置
            ImportParams params = new ImportParams();

            // 表头一行
            params.setHeadRows(1);

            // 标题一行
            params.setTitleRows(1);

            // 代表导入这里是需要验证的（根据字段上的注解校验）
            params.setNeedVerify(true);

            // 设及一个自定义校验 （自定义校验名字不可重复）
            params.setVerifyHandler(batchAddCustomerExcelVerifyHandler);

            // 使用框架自身导入工具
            ExcelImportResult<BatchAddCustomerImportParam> result = ExcelImportUtil.importExcelMore(inputStream, BatchAddCustomerImportParam.class, params);


            // 导入成功的数据
            List<BatchAddCustomerImportParam> list = result.getList();
            list.forEach(l -> System.out.println("successList = " + l));

            // 失败结果集
            List<BatchAddCustomerImportParam> failList = result.getFailList();
            failList.forEach(l -> System.out.println("failList = " + l));

            // 拿到导出失败的工作簿
            Workbook failWorkbook = result.getFailWorkbook();

            //验证是否有失败的数据
            if (result.isVerifyFail()) {
                EasyPoiUtils.downLoadExcel("数据存在错误请查看", resp, failWorkbook);
            }
        }

        return "ok";
    }


    /**
     * 导出测试
     *
     * @param response the response
     */
    @GetMapping(value = "/excel/export")
    public void exportTest(HttpServletResponse response) {
        // 模拟数据库查询出来的数据
        List<BatchAddCustomerExportVO> data = Lists.newArrayList(
                BatchAddCustomerExportVO.builder().mobile("18588233764").remark("a").time(new DateTime()).build(),
                BatchAddCustomerExportVO.builder().mobile("18588233765").remark("b").time(new DateTime()).build(),
                BatchAddCustomerExportVO.builder().mobile("18588233766").remark("c").time(new DateTime()).build(),
                BatchAddCustomerExportVO.builder().mobile("18588233767").remark("d").time(new DateTime()).build()
        );
        EasyPoiUtils.exportExcel(data, BatchAddCustomerExportVO.class, "批量加好友导出测试",
                "批量加好友导出", "批量加好友", true, response);

        // 后面的代码会继续执行
        System.out.println("后面的代码会继续执行");
    }


}
